import {
	IUIEngineInputParam,
	IUIEngineModel,
	IUIEngineResult,
} from '@/core/interface';
import { UIEngine } from './ui-engine';

/**
 * 计数器界面引擎
 *
 * @export
 * @class TimerUIEngine
 * @extends {UIEngine<A>}
 * @template A
 */
export class TimerUIEngine<A> extends UIEngine<A> {
	/**
	 * 计数器标识
	 *
	 * @private
	 * @type {*}
	 * @memberof TimerUIEngine
	 */
	private timerId: any;

	/**
	 * 间隔时间
	 *
	 * @type {number}
	 * @memberof TimerUIEngine
	 */
	public timer: number = 6000;

	/**
	 * Creates an instance of TimerUIEngine.
	 * @param {IUIEngineModel} model
	 * @memberof TimerUIEngine
	 */
	public constructor(model: IUIEngineModel) {
		super(model);
		this.timer = model.timer ? model.timer : 6000;
	}

	/**
	 * 异步执行
	 *
	 * @param {IUIEngineInputParam<A>} args
	 * @return {*}  {Promise<IUIEngineResult>}
	 * @memberof TimerUIEngine
	 */
	public async asyncExcute(
		args: IUIEngineInputParam<A>
	): Promise<IUIEngineResult> {
		if (this.timerId) {
			return { ok: true, data: [] };
		}
		try {
			super.asyncExcute(args);
			this.timerId = setInterval(() => {
				super.asyncExcute(args);
			}, this.timer);
		} catch (error) {
			return { ok: false, data: [] };
		}
		return { ok: true, data: [] };
	}

	/**
	 * 同步执行
	 *
	 * @param {IUIEngineInputParam<A>} args
	 * @memberof TimerUIEngine
	 */
	public syncExcute(args: IUIEngineInputParam<A>) {
		if (this.timerId) {
			return { ok: true, data: [] };
		}
		try {
			super.syncExcute(args);
			this.timerId = setInterval(() => {
				super.syncExcute(args);
			}, this.timer);
		} catch (error) {
			return { ok: false, data: [] };
		}
		return { ok: true, data: [] };
	}

	/**
	 * 销毁
	 *
	 * @memberof TimerUIEngine
	 */
	public destroy() {
		if (this.timerId) {
			clearInterval(this.timerId);
		}
	}
}
